<template>
  <div class="card content-box">
    <el-container style="width: 100%; height: 100%">
      <el-aside style="width: 500px; height: 100%">
        <el-form ref="ruleFormRef" :rules="rules" :model="addProblemTemplateFormData" style="width: 100%" label-width="122px">
          <el-dialog title="选择服务目录" v-model="dialogServiceDirTableVisible">
            <div :style="{ height: '500px' }">
              <Custemerselect @send-data="sendCompanyNoData" />
            </div>
          </el-dialog>
          <el-dialog v-model="templateNameDialogVisible" title="内容模板名称" width="30%">
            <el-form style="width: 100%" label-width="120px">
              <el-form-item label="问题内容模板名称 :" prop="etitle">
                <el-input v-model="addProblemTemplateFormData.templateName" />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button type="primary" @click="templateNameBtn(ruleFormRef)">保存</el-button>
              </span>
            </template>
          </el-dialog>
          <div>
            <p>基本信息</p>
          </div>
          <el-form-item class="item" label="所属客户 :" prop="companyName" style="width: 98%">
            <el-input v-model="addProblemTemplateFormData.companyName" @click="dialogCompanyNoTableVisible = true" />
            <el-dialog title="选择客户" v-model="dialogCompanyNoTableVisible">
              <div :style="{ height: '500px' }">
                <Custemerselect @send-data="sendCompanyNoData" />
              </div>
            </el-dialog>
          </el-form-item>
          <el-form-item class="item" label="问题分类 :" prop="categoryName" style="width: 98%">
            <el-tree-select
              ref="RequestType"
              v-model="categorySelectValue"
              :data="categorySelectList"
              :render-after-expand="false"
              check-strictly
              check-on-click-node
              @change="changeProblemType"
            />
          </el-form-item>

          <el-form-item class="item" label="标题 :" prop="etitle" style="width: 98%">
            <el-input v-model="addProblemTemplateFormData.etitle" />
          </el-form-item>
          <el-form-item class="item" label="描述 :" style="width: 98%">
            <WangEditor v-model:value="content" />
          </el-form-item>
          <el-form-item label="期望完成日期 :" style="width: 98%">
            <el-date-picker
              v-model="addProblemTemplateFormData.overdueTime"
              type="datetime"
              placeholder="请选择开始时间"
              format="YYYY-MM-DD hh:mm:ss"
              value-format="YYYY-MM-DD hh:mm:ss"
              style="width: 98%"
            />
          </el-form-item>
          <el-form-item class="item" label="优先级 :" style="width: 98%">
            <el-tree-select
              v-model="prioritySelectValue"
              :data="prioritySelectList"
              :render-after-expand="false"
              check-strictly
              check-on-click-node
              @change="changepriority"
            />
          </el-form-item>
          <el-form-item class="item" label="影响 :" style="width: 98%">
            <el-tree-select
              v-model="effectRangeSelectValue"
              :data="effectRangeSelectList"
              :render-after-expand="false"
              check-strictly
              check-on-click-node
              @change="changeeffectRange"
            />
          </el-form-item>
          <el-form-item class="item" label="紧急度 :" style="width: 98%">
            <el-tree-select
              v-model="seriousnessSelectValue"
              :data="seriousnessSelectList"
              :render-after-expand="false"
              check-strictly
              check-on-click-node
              @change="changeseriousness"
            />
          </el-form-item>
        </el-form>
      </el-aside>
      <el-main>
        <el-button type="primary" @click="onSubmitForm(ruleFormRef)"> 保存 </el-button>
        <el-button type="primary" @click="backList"> 返回列表 </el-button>
        <!-- <el-button type="primary" @click="testbtn"> 测试 </el-button> -->
        <!-- <el-button type="primary" @click="serviceDir"> 服务目录 </el-button> -->
        <div>
          <p>详细信息</p>
        </div>
        <el-tabs v-model="activeName">
          <el-tab-pane label="扩展信息" name="kzxx">
            <form-create v-model="formData" v-model:api="formApi" :option="option" :rule="formCreateRules" />
          </el-tab-pane>
          <el-tab-pane label="关联配置项" name="first">
            <el-button type="primary" @click="selectCiDialogVisible = true"> 添加 </el-button>
            <el-dialog title="选择关联配置项" v-model="selectCiDialogVisible">
              <div :style="{ height: '500px' }">
                <moreSelectCi @send-data="sendCiData" />
              </div>
            </el-dialog>
            <ProTable
              ref="ciProTable"
              row-key="id"
              :indent="20"
              :data="ciList"
              :columns="ciColumns"
              :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
            >
              <!-- 表格操作 -->
              <template #operation="scope">
                <el-button type="primary" link @click="deleteci(scope.$index)">删除</el-button>
              </template>
            </ProTable>
          </el-tab-pane>
          <el-tab-pane label="附件" name="second">
            <el-button type="primary" @click="addAttachment"> 添加附件 </el-button>
            <ProTable
              ref="attachmentProTable"
              row-key="id"
              :indent="20"
              :data="attachmentList"
              :columns="attachmentColumns"
              :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
            >
              <!-- 表格操作 -->
              <template #operation="scope">
                <el-button type="primary" link @click="deleteattachment(scope.$index)">删除</el-button>
              </template>
            </ProTable>
          </el-tab-pane>
          <el-tab-pane label="关联服务" name="glfw">
            <el-tree-select
              style="width: 360px"
              v-model="serviceDirectorySelectValue"
              :data="serviceDirectorySelectList"
              multiple
              :render-after-expand="false"
              show-checkbox
              check-strictly
              check-on-click-node
            />
            <el-button type="primary" @click="addServiceDir"> 添加 </el-button>
            <!-- <el-dialog title="选择关联配置项" v-model="selectCiDialogVisible">
					    <div :style="{ height: '500px' }">
					      <moreSelectCi @send-data="sendCiData" />
					    </div>
					  </el-dialog> -->
            <ProTable
              ref="serviceDirectoryProTable"
              row-key="id"
              :indent="20"
              :data="serviceDirectoryList"
              :columns="serviceDirectoryColumns"
              :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
            >
              <!-- 表格操作 -->
              <template #operation="scope">
                <el-button type="primary" link @click="deleteserviceDirectory(scope.$index)">删除</el-button>
              </template>
            </ProTable>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>

    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="ts" name="basicForm">
import { ElMessage, FormInstance, FormRules, ElMessageBox } from "element-plus";
import { ref, reactive, onMounted, onBeforeUnmount, defineComponent } from "vue";
import { getjggl, emailtest, emailtestexchange, testSMSAccount, getjgglmessage, mergeCompany } from "@/api/modules/jggl";
import Userselect from "@/views/tools/userSelectbyOrgNo/index.vue";
import { isTelOrFax, isEmail } from "@/utils/eleValidate";
import WangEditor from "@/components/WangEditor/index.vue";
import Custemerselect from "@/views/tools/custemerSelect/index.vue";
import { useRoute, useRouter } from "vue-router";
import { dataDictionaryItemsfindByCode, getCategoryTreeAllData } from "@/api/modules/dataDictionary";
import {
  findPageScheduledTask,
  saveScheduledTask,
  deleteScheduledTask,
  findScheduledTaskById,
  editScheduledTask,
  uploadFile,
  saveRequestTemplate,
  saveProblemTemplate,
  findSubCategorysByEvenId,
  findAttributeList,
  findByTemplateId,
  findCiByIds
} from "@/api/modules/systemTools";
import { useTabsStore } from "@/stores/modules/tabs";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import moreSelectCi from "@/views/tools/moreCiSelect/index.vue";
import ImportExcel from "@/views/tools/uploadFile/index.vue";
import { getCurrentLoginUser } from "@/api/modules/accessController";
import { saveRequest } from "@/api/modules/request";
import formCreate from "@form-create/element-ui"; // 引入 FormCreate
import { editProblemBaseInfo, problemEdit, findAllEventAttachment, findEventEav } from "@/api/modules/problemManagement";
import { deleteEventAttachment } from "@/api/modules/eventManagement";
import { uploadAttr, saveEventAttachment } from "@/api/modules/common";

const content = ref("");
const router = useRouter();
const route = useRoute();
const tabStore = useTabsStore();
const UserselectRef = ref<InstanceType<typeof Userselect> | null>(null);

const templateNameDialogVisible = ref(false);
const templateNameBtn = async (formEl: FormInstance | undefined) => {
  if (addProblemTemplateFormData.templateName == "") {
    ElMessage({
      type: "error",
      message: "模板名称不能为空"
    });
    return;
  }
  onSubmitForm(formEl);
  templateNameDialogVisible.value = false;
};

const serviceDirectoryProTable = ref<ProTableInstance>();
const serviceDirectoryList = ref<any>([]);

const serviceDirectoryColumns = reactive<ColumnProps<resCIList>[]>([
  { prop: "id", label: "ID", sortable: true },
  { prop: "cname", label: "服务名称", sortable: true, width: 260 },
  { prop: "operation", label: "操作项", fixed: "right", width: 200 }
]);
//关联配置项开始
const ciProTable = ref<ProTableInstance>();
const ciList = ref<any>([]);

const serviceDirectorySelectValue = ref();
const serviceDirectorySelectList = ref<any>([]);

const selectCiDialogVisible = ref(false);
const ciColumns = reactive<ColumnProps<resCIList>[]>([
  { prop: "cino", label: "固定资产编号", sortable: true },
  { prop: "ciname", label: "名称", sortable: true, width: 260 },
  { prop: "categoryName", label: "分类", sortable: true, width: 260 },
  { prop: "status", label: "状态", sortable: true, width: 260 },
  { prop: "operation", label: "操作项", fixed: "right", width: 200 }
]);

// 删除
const deleteci = async (index: any) => {
  ciList.value.splice(index, 1);
};

// 添加关联服务
const addServiceDir = () => {
  serviceDirectorySelectValue.value.forEach(function (element2) {
    traverseTree(serviceDirectorySelectList.value[0], node => {
      if (node.data == element2.toString()) {
        console.log("选中");
        console.log(node);
        let tmp = {
          id: node.attr.id,
          cname: node.attr.cname
        };
        //去重
        let addflag = true;
        serviceDirectoryList.value.forEach(val => {
          if (val.id == tmp.id) {
            addflag = false;
          }
        });
        if (addflag == true) {
          serviceDirectoryList.value.push(tmp);
        } else {
          ElMessage({
            type: "info",
            message: "存在相同数据 :   " + tmp["cname"] + "，  已自动过滤重复数据"
          });
        }
      }
    });
  });
};

//选中资产子组件弹窗回调方法
const sendCiData = (data: [resCIList]) => {
  if (data.length > 0) {
    for (let i = 0; i < data.length; i++) {
      //去重
      let addflag = true;
      ciList.value.forEach(val => {
        if (val.ciId == data[i].ciId) {
          addflag = false;
        }
      });
      if (addflag == true) {
        ciList.value.push(data[i]);
      } else {
        ElMessage({
          type: "info",
          message: "存在相同配置 :   " + data[i]["ciname"] + "，  已自动过滤重复配置"
        });
      }
    }
  }
  selectCiDialogVisible.value = false;
};
export interface resCIList {
  ciname: string;
  cino: string;
  categoryName: string;
  categoryNo: string;
  status: string;
  ciId: number;
  attachmentStr: string;
  fileName: string;
  beginTime: string;
  companyName: string;
  companyNo: number;
  contractName: string;
  contractNo: number;
  dataFlag: number;
  description: string;
  dialect: string;
  endTime: string;
  finishTime: number;
  flagName: string;
  lastUpdater: string;
  packageName: string;
  respondTime: number;
  ruleName: string;
  ruleNo: number;
  rulePackageNo: number;
  salience: number;
  showFinishTime: string;
  showRespondTime: string;
  beforeOrAfter: boolean;
  beforeOrAfterStr: string;
  timeStr: string;
}
//关联配置项结束

//附件开始
const attachmentProTable = ref<ProTableInstance>();
const attachmentList = ref<any>([]);
const attachmentColumns = reactive<ColumnProps<resCIList>[]>([
  { prop: "fileName", label: "文件名称" },
  { prop: "operation", label: "操作项", fixed: "right", width: 200 }
]);
const uploadFileRes = async (param: any) => {
  let res = JSON.parse(JSON.stringify(param));
  let attachmentStr = res.fileName + "==" + res.msg + "==" + res.fileSize + "-s-";
  // let attachment = {
  //   fileName: res.fileName,
  //   attachmentStr: attachmentStr
  // };
  // attachmentList.value.push(attachment);

  saveEventAttachment({
    creator: addProblemTemplateFormData.creator,
    eno: addProblemTemplateFormData.eno,
    eventType: "itsm.problem",
    attachmentStr: attachmentStr
  })
    .then(() => {
      getAtt();
      // loading.value = false;

      // getList();
    })
    .catch(() => {
      // loading.value = false;
    });
};
// 添加附件
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const addAttachment = () => {
  const params = {
    title: "",
    tempApi: uploadFile,
    importApi: uploadFile,
    getTableList: ciProTable.value?.getTableList,
    addAttachmentMethod: uploadFileRes
  };
  dialogRef.value?.acceptParams(params);
};
// 删除附件
const deleteattachment = async (index: any) => {
  ElMessageBox.confirm("确定要删除该附件？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(() => {
      // loading.value = true;
      // 事件删除附件
      console.log(attachmentList.value[index]);
      let newElement = JSON.parse(JSON.stringify(attachmentList.value[index]));
      deleteEventAttachment({
        eno: newElement["eno"],
        ids: newElement["id"]
      })
        .then(() => {
          getAtt();
          // loading.value = false;
          ElMessage.success("删除成功");
          // attachmentList.value.splice(index, 1);
        })
        .catch(() => {
          // loading.value = false;
        });
    })
    .catch(e => {
      console.log(e);
      // cancel operation
    });

  // attachmentList.value.splice(index, 1);
};
//附件结束
const deleteserviceDirectory = async (index: any) => {
  serviceDirectoryList.value.splice(index, 1);
};

//开始
//请求客户
const dialogCompanyNoTableVisible = ref(false);
const dialogCreatedByTableVisible = ref(false); //创建人
const categorySelectValue = ref();
const categorySelectList = ref<any>([]);

//来源选择结束
//优先级选择开始
const prioritySelectValue = ref();
const prioritySelectList = ref<any>([]);
const changepriority = (val: any) => {
  prioritySelectList.value.forEach(function (element) {
    let newElement = JSON.parse(JSON.stringify(element));
    if (newElement.value == val.toString()) {
      addProblemTemplateFormData.priorityNo = newElement.dcode;
    }
  });
};
//优先级选择结束
//影响选择开始
const effectRangeSelectValue = ref();
const effectRangeSelectList = ref<any>([]);
const changeeffectRange = (val: any) => {
  effectRangeSelectList.value.forEach(function (element) {
    let newElement = JSON.parse(JSON.stringify(element));
    if (newElement.value == val.toString()) {
      addProblemTemplateFormData.effectRangeNo = newElement.dcode;
    }
  });
};
//影响结束

//紧急度选择开始
const seriousnessSelectValue = ref();
const seriousnessSelectList = ref<any>([]);
const changeseriousness = (val: any) => {
  seriousnessSelectList.value.forEach(function (element) {
    let newElement = JSON.parse(JSON.stringify(element));
    if (newElement.value == val.toString()) {
      addProblemTemplateFormData.seriousnessNo = newElement.dcode;
    }
  });
};
//紧急度结束

// 父组件的值
const fatherValue = ref({ orgNo: 1 });

const addProblemTemplateFormData = reactive({
  creator: "",
  companyNo: 1,
  etitle: "",
  templateType: "problem",
  formId: "",
  companyName: "",
  createdByName: "",
  createdByNo: "",
  categoryName: "",
  categoryNo: "",
  edesc: "",
  priorityNo: "",
  effectRangeNo: "",
  seriousnessNo: "",
  attachmentStr: "",
  templateName: "",
  templateId: "",
  overdueTime: "",
  eno: ""
});

//客户选择子组件弹窗回调方法
const sendCompanyNoData = (data: any) => {
  dialogCompanyNoTableVisible.value = false;
  addProblemTemplateFormData.companyNo = data.orgNo;
  addProblemTemplateFormData.companyName = data.orgName;
  fatherValue.value.orgNo = data.orgNo;
};

// ProTable 实例

const formData = ref({});
const formApi = ref(null);
const formCreateRules = ref<any>([]);
const formCreateRules2 = ref<any>([]);
const option = ref({
  submitBtn: false
});
const dataDictionaryFlagList = ref<any>([]);
//问题分类选择
const changeProblemType = (val: any) => {
  traverseTree(categorySelectList.value[0], node => {
    if (node.value == val.toString()) {
      if ((node.children as any).length > 0) {
        // console.log("非叶子节点")
        ElMessage.info("请选择叶子节点");
        categorySelectValue.value = addProblemTemplateFormData.categoryName;
      } else {
        addProblemTemplateFormData.categoryNo = node.attr.id;
        addProblemTemplateFormData.categoryName = node.attr.cname;
        addProblemTemplateFormData.etitle = node.attr.cname;
        // ,findAttributeList
        findSubCategorysByEvenId(node.attr.eventId).then(res => {
          if (res.toString() == "true") {
            if (formCreateRules.value.length != 0) {
              formCreateRules.value.length = 0;
            }
            if (dataDictionaryFlagList.value.length != 0) {
              dataDictionaryFlagList.value.length = 0;
            }
            if (node.attr.eavId != undefined && node.attr.eavId != null)
              findAttributeList(node.attr.eavId).then(resAttList => {
                (resAttList as any).forEach(function (element) {
                  if (element.attrType == "String") {
                    formCreateRules.value.push({
                      type: "input",
                      field: element.attrName,
                      title: element.attrAsName,
                      value: "",
                      col: {
                        span: 10
                      }
                    });
                  }
                  if (element.attrType == "Radio") {
                    formCreateRules.value.push({
                      type: "radio",
                      field: element.attrName,
                      title: element.attrAsName,
                      value: "",
                      col: {
                        span: 12
                      },
                      options: [{ value: true, label: element.attrAsName, disabled: false }]
                    });
                  }
                  if (element.attrType == "checkbox") {
                    formCreateRules.value.push({
                      type: "checkbox",
                      field: element.attrName,
                      title: element.attrAsName,
                      value: "",
                      options: [{ value: true, label: element.attrAsName, disabled: false }]
                    });
                  }
                  if (element.attrType == "Double") {
                    formCreateRules.value.push({
                      type: "InputNumber",
                      field: element.attrName,
                      title: element.attrAsName,
                      value: "",
                      props: {
                        precision: 3
                      }
                    });
                  }
                  if (element.attrType == "Integer") {
                    formCreateRules.value.push({
                      type: "InputNumber",
                      field: element.attrName,
                      title: element.attrAsName,
                      value: "",
                      props: {
                        precision: 0
                      }
                    });
                  }
                  if (element.attrType == "Date") {
                    formCreateRules.value.push({
                      type: "DatePicker",
                      field: element.attrName,
                      title: element.attrAsName,
                      value: "",
                      props: {
                        type: "datetime",
                        placeholder: "请选择日期"
                      }
                    });
                  }
                  if (element.attrType == "Lob") {
                    formCreateRules.value.push({
                      type: "input",
                      field: element.attrName,
                      title: element.attrAsName,
                      value: "",
                      props: {
                        type: "textarea "
                      }
                    });
                  }
                  if (element.attrType == "DataDictionaray") {
                    let optionList = [];
                    //优先级priority
                    dataDictionaryItemsfindByCode(element.attrdataDictionary).then(res => {
                      (res as any).forEach(function (element) {
                        element["lable"] = element["dname"];
                        element["value"] = element["dname"];
                      });
                      optionList = res as any;
                      formCreateRules.value.push({
                        type: "select",
                        field: element.attrName,
                        title: element.attrAsName,
                        value: "",
                        options: optionList
                      });
                      let dataDictionaryFlagListObj = {
                        id: element.attrName,
                        attrdataDictionary: element.attrdataDictionary,
                        dataList: optionList
                      };
                      dataDictionaryFlagList.value.push(dataDictionaryFlagListObj);
                    });
                  }
                });
              });
          }
        });
      }
    }
  });
  console.log(val);
};

const onSubmitFormPre = async (formEl: FormInstance | undefined) => {
  templateNameDialogVisible.value = true;
};
const onSubmitForm = async (formEl: FormInstance | undefined) => {
  if (content.value == null || content.value == "") {
    ElMessage.error("描述不能为空");
  }
  addProblemTemplateFormData.edesc = content.value.toString();
  let idsStr = "";
  for (let i = 0; i < ciList.value.length; i++) {
    if (idsStr == "") {
      idsStr = "?cinos=" + ciList.value[i].ciId;
    } else {
      idsStr = idsStr + "&cinos=" + ciList.value[i].ciId;
    }
  }
  let serviceDirStr = "";
  for (let i = 0; i < serviceDirectoryList.value.length; i++) {
    if (serviceDirStr == "") {
      serviceDirStr = "problemDTO.serviceDirectoryNos=" + serviceDirectoryList.value[i].id;
    } else {
      serviceDirStr = serviceDirStr + "&problemDTO.serviceDirectoryNos=" + serviceDirectoryList.value[i].id;
    }
  }

  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      //校验成功
      //扩展数据saveData
      let saveData = {};
      Object.keys(formData.value).forEach(key => {
        saveData[`${key}`] = `${formData.value[key]}`;
      });
      //识别数据字典名字改为编号
      for (let i = 0; i < dataDictionaryFlagList.value.length; i++) {
        Object.keys(saveData).forEach(key => {
          if ((dataDictionaryFlagList.value[i].id = `${key}`)) {
            (dataDictionaryFlagList.value[i].dataList as any).forEach(function (element) {
              if (element["value"] == `${saveData[key]}`) {
                saveData[`${key}`] = element.dcode;
              }
            });
          }
        });
      }
      editProblemBaseInfo(addProblemTemplateFormData, "problemDTO", idsStr, serviceDirStr, saveData).then(res => {
        console.log(res);
        ElMessage.success("编辑成功");
        tabStore.removeTabs(route.fullPath);
        router.push(`/problemManagement/index?pageNo=${Math.random().toFixed(3)}`);
      });
      // ElMessage.success("保存成功");
    } else {
      ElMessage.error("请正确填写表单");
    }
  });
  console.log(content.value);
  //getjggl(fsyxData, "emailServerDTO");
  // ElMessage.success("提交的发送邮箱数据为 : " + JSON.stringify(addProblemTemplateFormData));
};

const testbtn = async () => {
  let saveData = {};
  Object.keys(formData.value).forEach(key => {
    saveData[`${key}`] = `${formData.value[key]}`;
  });
  //识别数据字典名字改为编号
  for (let i = 0; i < dataDictionaryFlagList.value.length; i++) {
    Object.keys(saveData).forEach(key => {
      if ((dataDictionaryFlagList.value[i].id = `${key}`)) {
        (dataDictionaryFlagList.value[i].dataList as any).forEach(function (element) {
          if (element["value"] == `${saveData[key]}`) {
            saveData[`${key}`] = element.dcode;
          }
        });
      }
    });
  }
  console.log(saveData);
};
// 返回列表
const backList = async () => {
  tabStore.removeTabs(route.fullPath);
  router.push(`/problemManagement/index?pageNo=${Math.random().toFixed(3)}`);
};
const dialogServiceDirTableVisible = ref(false);
// 服务目录
const serviceDir = async () => {
  dialogServiceDirTableVisible.value = true;
  tabStore.removeTabs(route.fullPath);
  router.push(`/system/tools/regularTaskManagement?pageNo=${Math.random().toFixed(3)}`);
};

//结束

const ruleFormRef = ref<FormInstance>();
const activeName = ref("kzxx");

const getAtt = () => {
  attachmentList.value = [];
  findAllEventAttachment(addProblemTemplateFormData.eno).then(attres => {
    for (let i = 0; i < (attres as any).length; i++) {
      let attachment = {
        fileName: attres[i]["attachmentName"],
        attachmentStr: attres[i]["attachmentName"] + "==" + attres[i]["url"] + "==" + attres[i]["size"] + "-s-",
        id: attres[i]["aid"],
        eno: attres[i]["eno"]
      };
      attachmentList.value.push(attachment);
    }
  });
};

const rules = reactive<FormRules>({
  companyName: [{ required: true, message: "请选择公司", trigger: "blur" }],
  createdByName: [{ required: true, message: "请选择请求用户", trigger: "blur" }],
  categoryName: [{ required: true, message: "请选择请求分类", trigger: "blur" }],
  etitle: [{ required: true, message: "请输入标题", trigger: "blur" }],
  edesc: [{ required: true, message: "请输入描述", trigger: "blur" }]
});
onMounted(() => {
  //加载公司信息
  getjgglmessage().then(res => {
    let newParams = JSON.parse(JSON.stringify(res));
    addProblemTemplateFormData.companyName = newParams.companyName;
    addProblemTemplateFormData.companyNo = newParams.companyNo == 0 ? 1 : newParams.companyNo;
  });
  //加载用户数据
  getCurrentLoginUser().then(res => {
    let newRes = JSON.parse(JSON.stringify(res));
    addProblemTemplateFormData.createdByNo = newRes.userId;
    addProblemTemplateFormData.createdByName = newRes.fullName;

    addProblemTemplateFormData.creator = newRes.loginName;
  });
  //分类选择树
  getCategoryTreeAllData("Problem").then(res => {
    // 使用traverseTree遍历树
    traverseTree(res as any, node => {
      node["lable"] = node.attr.cname;
      node["value"] = node.attr.cname;
    });
    let k: any[] = [];
    k.push(res);
    categorySelectList.value = k;
  });

  //优先级priority
  dataDictionaryItemsfindByCode("priority").then(res => {
    (res as any).forEach(function (element) {
      element["lable"] = element["dname"];
      element["value"] = element["dname"];
    });
    prioritySelectList.value = res as any;
  });
  //影响effectRange
  dataDictionaryItemsfindByCode("effectRange").then(res => {
    (res as any).forEach(function (element) {
      element["lable"] = element["dname"];
      element["value"] = element["dname"];
    });
    effectRangeSelectList.value = res as any;
  });

  dataDictionaryItemsfindByCode("seriousness").then(res => {
    (res as any).forEach(function (element) {
      element["lable"] = element["dname"];
      element["value"] = element["dname"];
    });
    seriousnessSelectList.value = res as any;
  });

  //服务目录
  getCategoryTreeAllData("Service").then(res => {
    // 使用traverseTree遍历树
    traverseTree(res as any, node => {
      node["lable"] = node.attr.cname;
      node["value"] = node.attr.cname;
    });
    serviceDirectorySelectList.value = [res as any];
  });

  //编辑时加载数据
  let query = JSON.parse(JSON.stringify(route.query));
  // findByTemplateId findCiByIds
  if (query.id != undefined) {
    problemEdit(query.id).then(res => {
      let newParams = JSON.parse(JSON.stringify(res));
      let ciIds = "";

      ciList.value = newParams.cigDTO;
      findAllEventAttachment(query.id).then(attres => {
        for (let i = 0; i < (attres as any).length; i++) {
          let attachment = {
            fileName: attres[i]["attachmentName"],
            attachmentStr: attres[i]["attachmentName"] + "==" + attres[i]["url"] + "==" + attres[i]["size"] + "-s-",
            id: attres[i]["aid"],
            eno: attres[i]["eno"]
          };
          attachmentList.value.push(attachment);
        }
      });
      let serviceNos = newParams.porblemEvent == undefined ? {} : newParams.porblemEvent;
      for (let i = 0; i < serviceNos.length; i++) {
        let tmpservice = {
          id: serviceNos[i]["eventId"],
          cname: serviceNos[i]["eventName"]
        };
        serviceDirectoryList.value.push(tmpservice);
      }
      addProblemTemplateFormData.creator = newParams.creator == undefined ? "" : newParams.creator;
      addProblemTemplateFormData.companyNo = newParams.companyNo == undefined ? "" : newParams.companyNo;
      addProblemTemplateFormData.etitle = newParams.etitle == undefined ? "" : newParams.etitle;
      addProblemTemplateFormData.companyName = newParams.companyName == undefined ? "" : newParams.companyName;
      addProblemTemplateFormData.createdByName = newParams.createdByName == undefined ? "" : newParams.createdByName;
      addProblemTemplateFormData.createdByNo = newParams.createdByNo == undefined ? "" : newParams.createdByNo;
      addProblemTemplateFormData.eno = newParams.eno == undefined ? "" : newParams.eno;
      content.value = newParams.edesc == undefined ? "" : newParams.edesc;
      addProblemTemplateFormData.priorityNo = newParams.priorityNo == undefined ? "" : newParams.priorityNo;
      addProblemTemplateFormData.effectRangeNo = newParams.effectRangeNo == undefined ? "" : newParams.effectRangeNo;
      addProblemTemplateFormData.seriousnessNo = newParams.seriousnessNo == undefined ? "" : newParams.seriousnessNo;
      addProblemTemplateFormData.categoryName = newParams.categoryName == undefined ? "" : newParams.categoryName;
      addProblemTemplateFormData.categoryNo = newParams.categoryNo == undefined ? "" : newParams.categoryNo;
      changeProblemType(addProblemTemplateFormData.categoryName);
      categorySelectValue.value = addProblemTemplateFormData.categoryName;

      findEventEav(addProblemTemplateFormData.eno).then(reseav => {
        if (reseav != null) {
          // let attrVals = newParams.attrVals == undefined ? {} : newParams.attrVals;
          let attrVals = reseav;
          setTimeout(() => {
            Object.keys(attrVals).forEach(key => {
              Object.keys(formData.value).forEach(key2 => {
                if (`${key}` == `${key2}`) {
                  if (`${attrVals[key]}` == "true") {
                    formData.value[`${key2}`] = true;
                  } else {
                    formData.value[`${key2}`] = `${attrVals[key]}`;
                  }
                }
              });
            });
          }, 2200);
        }
      });
      addProblemTemplateFormData.attachmentStr = newParams.attachmentStr == undefined ? "" : newParams.attachmentStr;
      addProblemTemplateFormData.overdueTime = newParams.overdueTime == undefined ? "" : newParams.overdueTime;
      addProblemTemplateFormData.templateName = newParams.templateName == undefined ? "" : newParams.templateName;
      addProblemTemplateFormData.templateId = newParams.templateId == undefined ? "" : newParams.templateId;
      addProblemTemplateFormData.templateType = newParams.templateType == undefined ? "" : newParams.templateType;
      addProblemTemplateFormData.formId = newParams.formId == undefined ? "" : newParams.formId;
      prioritySelectList.value.forEach(function (element) {
        let newElement = JSON.parse(JSON.stringify(element));
        if (newElement.dcode == addProblemTemplateFormData.priorityNo) {
          prioritySelectValue.value = newElement.value;
        }
      });
      effectRangeSelectList.value.forEach(function (element) {
        let newElement = JSON.parse(JSON.stringify(element));
        if (newElement.dcode == addProblemTemplateFormData.effectRangeNo) {
          effectRangeSelectValue.value = newElement.value;
        }
      });

      seriousnessSelectList.value.forEach(function (element) {
        let newElement = JSON.parse(JSON.stringify(element));
        if (newElement.dcode == addProblemTemplateFormData.seriousnessNo) {
          seriousnessSelectValue.value = newElement.value;
        }
      });
    });
  }
});

interface TreeNode {
  value: any;
  lable: any;
  children?: TreeNode[];
  id: string;
  name: string;
  attr: any;
  data: any;
}

function traverseTree(node: TreeNode, callback: (node: TreeNode) => void) {
  callback(node);
  if (node.children) {
    node.children.forEach(child => traverseTree(child, callback));
  }
}
</script>

<style scoped lang="scss">
.item {
  width: 500px;
}
</style>
